import { selectData } from './createSelectData';
import { getChannelTypes } from '/imports/models/ChannelTypes';

Template.createChannelInfoType.onRendered(function() {
  this.autorun(() => {
    let arr = [];

    const channeltypes = getChannelTypes();
    channeltypes.forEach((type) => {
      let obj = {
        id: type.name + '_' + type.details,
        text: type.details
      };

      if (type.name == 'group') {
        obj.selected = true;
      }

      arr.push(obj);
    });

    if (this.data.id && typeof this.data.id === 'string') {
      for (let i = 0; i < arr.length; i++) {
        arr[i].selected = false;
        if (this.data.id == arr[i].id) {
          arr[i].selected = true;
        }
      }
    }

    $('#channel-info-type').select2({
      data: arr,
      width: '100%',
      theme: 'class',
      minimumResultsForSearch: Infinity
    });
  });
});

Template.createChannelInfoNumberOfPeople.onRendered(function() {
  let arr = selectData.numberOfPeople;

  this.autorun(() => {
    if (this.data.id && typeof this.data.id === 'string') {
      for (let i = 0; i < arr.length; i++) {
        arr[i].selected = false;
        if (this.data.id == arr[i].id) {
          arr[i].selected = true;
        }
      }
    }

    $('#channel-info-number-of-people').select2({
      data: arr,
      width: '100%',
      theme: 'class',
      minimumResultsForSearch: Infinity
    });
  });
});

Template.createChannelInfoPolicy.onRendered(function() {
  let arr = selectData.policy;

  this.autorun(() => {
    if (this.data.id && typeof this.data.id === 'string') {
      for (let i = 0; i < arr.length; i++) {
        arr[i].selected = false;
        if (this.data.id == arr[i].id) {
          arr[i].selected = true;
        }
      }
    }

    $('#channel-info-policy').select2({
      data: arr,
      width: '100%',
      theme: 'class',
      minimumResultsForSearch: Infinity
    });
  });
  
  $('#channel-info-policy').on('change', function (event) {
    if (event.target.value == 'public') {
      $('#channel-info-policy-help').text('所有地方的所有人都可以进入');
      $('label[for="channel-info-apply-policy"]').text('他人需要申请才能加入你的频道？');
    }

    if (event.target.value == 'private') {
      $('#channel-info-policy-help').text('只有受邀成员可以进入频道');
      $('label[for="channel-info-apply-policy"]').text('允许他人搜索并且申请加入？');
    }
  });
});

Template.createChannelInfoApplyPolicy.onRendered(function() {
  this.autorun(() => {
    if (this.data && typeof this.data.apply === 'boolean') {
      $('#channel-info-apply-policy').prop('checked', this.data.apply);
    }
  });
});